<template>
  <div class="style-information-component">
    <el-form-item label="商品图片" />
    <div class="upload-wrap">
      <el-upload
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :headers="headers"
        :data="dataObj"
        :file-list="form.imgs"
        :limit="20"
        :on-success="handleImageSuccess"
        :action="action"
      >
        <i slot="default" class="el-icon-plus" />
        <div slot="file" slot-scope="{ file }">
          <img class="el-upload-list__item-thumbnail" :src="file.imgPath" />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <i class="el-icon-zoom-in" />
            </span>
            <span
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
            >
              <i class="el-icon-delete" />
            </span>
          </span>
        </div>
      </el-upload>
    </div>
    <!-- <el-form-item label="款式设置">
      <el-radio-group v-model="form.attrStyle" @change="changeAttrStyle">
        <el-radio :label="0">单款式</el-radio>
        <el-radio :label="1">多款式</el-radio>
      </el-radio-group>
    </el-form-item> -->
    <div class="style-container">
      <div class="single-style">
        <el-table
          :data="skuList"
          style="width: 100%"
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
        >
          <el-table-column label="名称">
            <template slot-scope="scope">
              <el-input
                v-model="singleStyle.skuValue"
                :sss="scope"
                maxlength="40"
              />
            </template>
          </el-table-column>
          <el-table-column label="规格">
            <template slot-scope="scope">
              <el-input
                v-model="singleStyle.skuValue"
                :sss="scope"
                maxlength="40"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价（元/吨）">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.price" type="number" oninput="value=value.replace(/-/, '')" /> -->
              <el-input-number
                v-model="scope.row.price"
                :controls="false"
                :min="0"
                :precision="2"
                :step="0.01"
              />
            </template>
          </el-table-column>

          <el-table-column label="报价说明">
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.weight" type="number" oninput="value=value.replace(/-/, '')" /> -->
              <el-input-number
                v-model="scope.row.weight"
                :controls="false"
                :min="0"
                :precision="2"
                :step="0.01"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <div class="dialog-footer">
      <el-button >取 消</el-button>
      <el-button type="primary">确 定</el-button>
    </div>

    <el-dialog
      :append-to-body="true"
      :visible.sync="dialogVisible"
      class="check-image-dialog"
      title="查看图片"
      center="center"
    >
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import { uploadUrl } from "@/utils/request";
import { getToken } from "@/utils/auth";
import priceRange from "./priceRage.vue";
export default {
  name: "AddComponent",
  filters: {
    attrValueFilter(map, list) {
      const hasChilds =
        list &&
        list.filter((skuAttr) => {
          const hasChild = skuAttr.values.some((attr) => {
            return attr.skuValue;
          });
          return skuAttr.skuName && hasChild;
        });
      if (!map) {
        return "";
      }
      const { code, valueCode } = map;
      let codeStr = "";
      hasChilds.map((item) => {
        const { values } = item;
        values &&
          values.some((attr) => {
            const isSome = item.code === code && attr.valueCode === valueCode;
            if (isSome) {
              codeStr = attr.skuValue;
            }
            return isSome;
          });
      });
      return codeStr;
    },
  },
  components: { priceRange },

  props: {
    form: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      newform: this.form,
      headers: {
        "Authorization-business": getToken(),
      },
      action: uploadUrl,
      dataObj: {
        folderId: 1,
      },
      fileList: [],
    };
  },
  computed: {
    skuAttrName() {
      return (
        this.form.skuAttrList &&
        this.form.skuAttrList.filter((skuAttr) => {
          const hasChilds = skuAttr.values.some((attr) => {
            return attr.skuValue;
          });
          return skuAttr.skuName && hasChilds;
        })
      );
    },
    singleStyle() {
      if (this.form.skuAttrList && this.form.skuAttrList[0]) {
        return this.form.skuAttrList && this.form.skuAttrList[0].values[0];
      }
      return {
        skuValue: "",
      };
    },
    skuList() {
      if (this.form.attrStyle === 0) {
        return this.form.skuList.slice(0, 1);
      }
      return this.form.skuList;
    },
  },
  watch: {
    "form.skuAttrList": {
      handler(newVal, oldVal) {
        // 判断是否有规格值
        const hasChilds =
          this.form.skuAttrList &&
          this.form.skuAttrList.filter((skuAttr) => {
            const hasChild = skuAttr.values.some((attr) => {
              return attr.skuValue;
            });
            return skuAttr.skuName && hasChild;
          });
        if (this.form.attrStyle === 1 && hasChilds.length) {
          this.skuFormat();
        }
        // console.log(newVal);
        // console.log(oldVal);
      },
      deep: true,
    },
    "form.skuList": {
      handler(newVal, oldVal) {
        // console.log(newVal);
        // console.log(oldVal);
      },
      deep: true,
    },
  },
  created() {
    this.headers.tenant = "MDAwMA==";
  },
  methods: {
    // proving1(e) {
    //   var keynum = window.event ? e.keyCode : e.which // 获取键盘码
    //   // var keychar = String.fromCharCode(keynum) // 获取键盘码对应的字符
    //   console.log(
    //     e.key
    //       .replace(/[^\d^\.]+/g, '')
    //       .replace('.', '$#$')
    //       .replace(/\./g, '')
    //       .replace('$#$', '.')
    //   )
    //   console.log(keynum)
    //   if (
    //     e.key
    //       .replace(/[^\d^\.]+/g, '')
    //       .replace('.', '$#$')
    //       .replace(/\./g, '')
    //       .replace('$#$', '.') === '' &&
    //     keynum !== 8
    //   ) {
    //     this.$message.warning('禁止输入中文或空')
    //     e.target.value = ' '
    //   }
    // },
    handleImageSuccess(response) {
      const url = response.data.url;
      this.form.imgs.push({
        imgPath: url,
      });
    },
    // 移除图片
    handleRemove(file) {
      const { imgPath } = file;
      this.form.imgs = this.form.imgs.filter((item) => {
        return item.imgPath !== imgPath;
      });
    },
    handleRemove1(file) {
      file.image = "";
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.imgPath;
      this.dialogVisible = true;
    },
    handleImageSuccess1(response, file, fileList) {
      const url = response.data.url;
      fileList[0].image = url;
    },
    del(row, index, arr) {
      console.log(row, index);
      // this.form.skuList.splice(index, 1);
      // console.log(this.form.skuAttrList);
      // console.log(this.form.skuList);
      console.log(arr);
    },
    //
    changeAttrStyle(index) {
      console.log(index);
      console.log(this.form);
      // if (index === 0) {
      //   this.form.skuAttrList = []
      // }
    },
    addSkuAttrList() {
      this.form.skuAttrList.push({
        code: "",
        skuName: "",
        values: [
          {
            skuValue: "",
            valueCode: "",
            image: "",
            isDelete: 0,
            sortOrder: 0,
          },
        ],
        isDelete: 0,
        needImg: 0,
        sortOrder: 0,
      });
    },
    addAttrValue(index) {
      this.form.skuAttrList[index].values.push({
        skuValue: "",
        valueCode: "",
        image: "",
      });
    },
    // 删除规格值
    delValue(index, index1) {
      const newList = JSON.parse(JSON.stringify(this.form.skuAttrList[index]));
      const valueObj = {
        code: newList.code,
        skuId: newList.skuId,
        valueCode: newList.values[index1].valueCode,
      };
      this.form.deletes.push(valueObj);
      this.form.skuAttrList[index].values.splice(index1, 1);
    },
    // 删除规格名
    delSkuAttrList(index) {
      const newList = JSON.parse(JSON.stringify(this.form.skuAttrList[index]));
      newList.values.forEach((item) => {
        const valueObj = {
          code: newList.code,
          skuId: newList.skuId,
          valueCode: "",
        };
        valueObj.valueCode = item.valueCode;
        this.form.deletes.push(valueObj);
      });
      this.form.skuAttrList.splice(index, 1);
    },
    delAttrValue1(row, index, arr) {},
    skuFormat() {
      const skuListArray = [];
      const result = {
        isDelete: 0,
        productId: "",
        skuAttrCodeDTOList: [
          {
            code: "",
            valueCode: "",
          },
        ],
        sku: "",
        skuImg: "",
        price: 0,
        originalPrice: 0,
        stockNumber: 0,
        weight: 0,
      };
      const doExchange = (arr, depth) => {
        const map = {
          arr: [],
        };
        for (var i = 0; i < arr[depth].length; i++) {
          map.arr.push(arr[depth][i]);
          const { code, valueCode, attrId } = arr[depth][i];
          result.skuAttrCodeDTOList[depth] = {
            code,
            valueCode,
            attrId,
          };
          if (depth !== arr.length - 1) {
            doExchange(arr, depth + 1);
          } else {
            skuListArray.push(JSON.parse(JSON.stringify(result)));
          }
        }
      };
      // this.form.skuList  = skuListArray
      // 获取规格值的所有组合
      const values = [];
      this.form.skuAttrList.map((skuItem, index) => {
        const attrList = [];
        skuItem.code = skuItem.code || "attr_code_" + index;
        const { code } = skuItem;
        skuItem.values &&
          skuItem.values.map((attrItem, index1) => {
            attrItem.valueCode = skuItem.valueCode || code + "_value_" + index1;
            const skuId = attrItem.skuId;
            const attrId = attrItem.attrId;
            if (attrItem.skuValue) {
              attrList.push({
                skuId,
                attrId,
                code,
                valueCode: attrItem.valueCode,
              });
            }
          });
        if (attrList.length) {
          values.push(attrList);
        }
      });
      // 相互组合
      if (values.length) {
        doExchange(values, 0);
      }
      this.form.skuList = skuListArray.map((sku1) => {
        const { skuAttrList, skuAttrCodeDTOList } = sku1;
        const skuAttrList1 = skuAttrCodeDTOList || skuAttrList;
        const skuMap = this.form.skuList.filter((sku2) => {
          const skuAttrList2 = sku2.skuAttrList;
          sku2.skuAttrCodeDTOList = skuAttrList2;
          if (!skuAttrList2) return false;
          const ids = [];
          skuAttrList1.filter((item) => ids.push(item.id));
          const result = skuAttrList2.every(
            (item) => ids.indexOf(item.attrValueId) !== -1
          );
          return result;
        });
        let selectMap = sku1;
        if (skuMap && skuMap.length) {
          selectMap = JSON.parse(JSON.stringify(skuMap[0]));
          selectMap.skuAttrCodeDTOList = skuAttrCodeDTOList;
        }
        return selectMap;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import url("../../../styles/elDialog.scss");

.dialog-footer{
  width: 200px;
  margin: 30px auto;
  display: flex;
  justify-content: space-between;
}
.style-information-component {
  width: 100%;
  min-height: 300px;
  padding: 24px;
  background-color: rgb(255, 255, 255);
  .el-form-item {
    margin-bottom: 10px;
  }
  .attr-value-list {
    display: flex;
    flex-wrap: wrap;
    .main-diagram {
      width: 180px;
      .span-wrap {
        position: relative;
        display: inline-block;
        margin-top: 10px;
        .attr-actions {
          line-height: 100px;
          position: absolute;
          width: 100%;
          height: 100%;
          left: 0;
          top: 0;
          cursor: default;
          text-align: center;
          color: #fff;
          opacity: 0;
          font-size: 20px;
          background-color: rgba(0, 0, 0, 0.5);
          -webkit-transition: opacity 0.3s;
          transition: opacity 0.3s;
          z-index: 1;
          &:hover {
            opacity: 1;
            .attr-preview {
              display: inline-block;
            }
            i {
              color: #fff;
              font-size: 20px;
            }
          }
        }
        .attr-preview {
          display: none;
          cursor: pointer;
          font-size: 20px;
          color: #fff;
        }
        .attr-delete {
          margin-left: 15px;
          color: #fff;
        }
      }
      .attr-value-img {
        width: 100%;
        height: 100%;
        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
    }
  }
  .m-8 {
    margin-right: 8px;
  }
  .upload-btn {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 110px;
    cursor: pointer;
    border: 2px dashed #2e60f8;
    border-radius: 2px;
    background-color: #f8f9fb;
    text-align: center;
    font-size: 20px;
    color: #2e60f8;
    i {
      color: #2e60f8;
      font-size: 20px;
    }
    .upload-title {
      margin-left: 10px;
      font-size: 14px;
    }
  }
  .upload-wrap {
    margin-bottom: 25px;
    .el-upload-list__item {
      transition: none !important;
    }
    .el-upload,
    .el-upload-list__item {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }
    .el-progress,
    .el-progress-circle {
      width: 80px !important;
      height: 80px !important;
    }
  }
  .sku-attr-list {
    .el-input {
      width: 180px;
    }
  }
  .single-style {
    .el-input {
      max-width: 180px;
    }
  }
  .add-attr-btn {
    margin-bottom: 25px;
  }
  .check-image-dialog {
    .el-dialog {
      margin-top: 25px;
      .el-dialog__body {
        img {
          max-width: 100%;
          max-height: 100%;
          height: 500px;
          object-fit: contain;
        }
      }
    }
  }
  .delImg {
    position: absolute;
    top: 12px;
    margin-left: -24px;
  }
  .delImg:hover {
    border-radius: 50%;
    color: #ffffff;
    background: #2e60f8;
    cursor: pointer;
  }
}
</style>
